<?php
/* +----------------------------------------------------------------------
// | 	xaoam.com
// |	author:am
// |	email:hi@xaoam.com
// |	bar模型
// +----------------------------------------------------------------------*/
namespace app\Admin\model;

use think\Model;
use think\Db;
use app\admin\validate\Bar as BarCheck;

class BarM extends Model {
	protected $table = "am_bar";
	
	protected function getStatusAttr($value,$data){
		        
				if($data['status'] == 1){
					return '<input type="checkbox" name="status" checked="" data-aid="' .$data["id"]. '" lay-skin="switch" lay-filter="switch" lay-text="ON|OFF">';
				}else{
					  return '<input type="checkbox" name="status" lay-skin="switch" data-aid="' .$data["id"]. '" lay-filter="switch" lay-text="ON|OFF">';
				}
	}
	protected function getSiteAttr($value,$data){
		$html = '<select name="site" lay-filter="select" data-aid="' . $data["id"] .'">';
		foreach(config('bar_site') as $key=>$row){
			if($key == $data['site']){
			$html .= '<option value="' . $key .'" selected>' . $row . '</option>';		
			}else{
			$html .= '<option value="' . $key .'">' . $row . '</option>';		
			}
		}
		$html .="</select>";
		return $html;
	}
	protected function getImageAttr($value,$data){
			$html = "";
			if($data['image']){
				$html .='<img src="' . $data['image'] . '">';
			}else{
				$html .= '编辑上传图片';
			}
		return $html;
	}
	/*验证器,验证*/
	protected function checkData($act,$data){
		$check = new BarCheck;
		if (!$check->scene($act)->check($data)) {
			$res['msg'] = $check->getError();
			$res['code'] = 0;
			header('Content-type:application/json; charset=utf-8');
			echo json_encode($res);
			exit();
		}
	}
	public function lists($limit){
		return $this->field('id,title,status,image,site')->paginate($limit);
	}
	public function find($data){
			return $this->where($data)->find();
	}
	public function cue($data){
		$this->checkData('cue',$data);
		return $this->update([
		    $data['field']  => $data['value'],
		],['id' => $data['id']]);
	}
	public function edit($data){
		$this->checkData('edit',$data);
		$data['status'] = isset($data['status'])?1:0;
		return $this->update($data);
	}
	public function add($data){
		$this->checkData('add',$data);
		$data['status'] = isset($data['status'])?1:0;
		//return $this->allowField('true')->cart($data);
		return $this->allowField(true)->save($data);
	}
	public function del($data){
		if(is_array($data['id'])){
			foreach($data['id'] as $row){
				$arr['id'] = $row;
				$this->checkData('del',$arr);
			}
		}else{
			$this->checkData('del',$data);
		}
		return $this->destroy($data['id']);
	}
}	